package com.wyw.controller;

import com.wyw.common.api.Result;
import org.apache.shiro.SecurityUtils;
import org.apache.shiro.authc.IncorrectCredentialsException;
import org.apache.shiro.authc.UnknownAccountException;
import org.apache.shiro.authc.UsernamePasswordToken;
import org.apache.shiro.subject.Subject;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;

@RestController
@RequestMapping("/user")
public class UserController {
    @GetMapping("login")
    public Result login(@RequestParam String userName, @RequestParam String password) {
        Result result = new Result();
        /*
         * 使用Shiro认证
         * */
        //1.获取subject对象
        Subject subject = SecurityUtils.getSubject();

        //2.封装用户数据
        System.out.println("userName:" + userName);
        System.out.println("password:" + password);
        UsernamePasswordToken token = new UsernamePasswordToken(userName, password);
        //3.执行登录方法
        try {
            subject.login(token);//如果它的底层不抛异常，就说明认证成功，它会调用UserRealm里面的doGetAuthenticationInfo方法执行认证细节
            result.setMessage("登录成功");
            result.setResult(true);
        } catch (UnknownAccountException e) {//doGetAuthenticationInfo中用户名不正确会抛出UnKnownAccountException异常
            result.setMessage("用户名不存在");
            result.setResult(false);
        } catch (IncorrectCredentialsException e) {//doGetAuthenticationInfo中密码不正确会抛出IncorrectCredentialsException异常
            result.setMessage("密码错误");
            result.setResult(false);
        }
        return result;

    }
}
